<script setup>
import dayjs from 'dayjs'
import { getTaskListByTime, getTcTaskInfoList, replaceTask } from '@/assets/api/task'
import { ElMessage } from 'element-plus'
import { useDictionary } from '@/use/use-dictionary'

const props = defineProps({
  projectId: [String, Number],
  user: Object,
})

const dict = useDictionary(['work_time'])

const weeks = ref([
  // {
  //   label: 50,
  //   days: [13, 14, 15, 16, 17, 18, 19],
  // },
])

const tasks = ref([
  {
    planBegintime: '2023-11-21 00:00:00',
    planEndtime: '2023-11-28 23:59:59',
  },
])

const visible = ref(false)

const taskForm = ref({
  taskId: null,
  planBegintime: null,
  planEndtime: null,
})

const replaceTaskForm = ref()

const checkFlag = ref({})

const formatStr = 'YYYY-MM-DD'

function openDialog(task) {
  taskForm.value = JSON.parse(JSON.stringify(task))
  replaceTaskForm.value = JSON.parse(JSON.stringify(task))
  checkFlag.value.start =
    dayjs(task.planBegintime).valueOf() <
    dayjs(dayjs(task.planBegintime).format(formatStr) + ` ${dict.getCode('work_time', '3')}`).valueOf()
      ? '1'
      : '3'
  checkFlag.value.end =
    dayjs(task.planEndtime).valueOf() <
    dayjs(dayjs(task.planEndtime).format(formatStr) + ` ${dict.getCode('work_time', '3')}`).valueOf()
      ? '2'
      : '4'
  visible.value = true
}

function handleTaskChange(taskId) {
  const task = filterTaskList.value.find((i) => i.taskId === taskId)
  taskForm.value = JSON.parse(JSON.stringify(task))
}

const allTaskList = ref([])

const filterTaskList = ref([])

const info = ref({})

const daterange = ref([dayjs(), dayjs().add(1, 'month')])

const loading = ref(false)

watch(
  () => props.user,
  (v) => {
    if (v.userId) {
      getTaskListByTimeData(daterange.value, v.userId)
    }
  },
  { immediate: true }
)

function getTaskListByTimeData(date, taskUserId) {
  if (date) {
    loading.value = true
    getTaskListByTime({
      projectId: props.projectId,
      taskUserId,
      planBegintime: dayjs(date[0]).format('YYYY-MM-DD'),
      planEndtime: dayjs(date[1]).format('YYYY-MM-DD'),
    }).then((res) => {
      loading.value = false
      if (res.code === 200) {
        weeks.value = []
        info.value = res.data
        const weekObj = new Map()
        res.data.holidaysList.forEach((i) => {
          const day = {
            label: dayjs(i.currentDay).format('MM-DD'),
            isRestDay: i.hhType === 2 || i.hhType === 3,
          }
          if (weekObj.has(i.currentWeek)) {
            weekObj.get(i.currentWeek).push(day)
          } else {
            weekObj.set(i.currentWeek, [day])
          }
        })
        const iterator = weekObj.entries()
        for (let i = 0; i < weekObj.size; i++) {
          const item = iterator.next().value
          weeks.value.push({
            label: item[0],
            days: item[1],
          })
        }
        tasks.value = res.data.tcTaskInfos
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}

getTcTaskInfoListData()

function getTcTaskInfoListData() {
  getTcTaskInfoList({ projectId: props.projectId, currentStatus: 1, taskProp: 5 }).then((res) => {
    if (res.code === 200) {
      allTaskList.value = res.rows
      filterTaskList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function filterMethod(value) {
  filterTaskList.value = allTaskList.value.filter((i) => i.taskTitle.includes(value) || i.taskCode.includes(value))
}

const rules = reactive({
  planBegintime: [
    {
      validator: (rule, value, callback) => {
        if (dayjs(taskForm.value.planBegintime).valueOf() < dayjs(replaceTaskForm.value.planBegintime).valueOf()) {
          callback(new Error('不能小于原计划开始时间'))
        } else if (dayjs(taskForm.value.planBegintime).valueOf() > dayjs(replaceTaskForm.value.planEndtime).valueOf()) {
          callback(new Error('不能大于原计划结束时间'))
        } else {
          callback()
        }
      },
    },
  ],
  planEndtime: [
    {
      validator: (rule, value, callback) => {
        if (dayjs(taskForm.value.planEndtime).valueOf() < dayjs(replaceTaskForm.value.planBegintime).valueOf()) {
          callback(new Error('不能小于原计划开始时间'))
        } else if (dayjs(taskForm.value.planEndtime).valueOf() > dayjs(replaceTaskForm.value.planEndtime).valueOf()) {
          callback(new Error('不能大于原计划结束时间'))
        } else {
          callback()
        }
      },
    },
  ],
})

function planStartTimeChange(date) {
  taskForm.value.planBegintime =
    dayjs(date).startOf('day').format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.start)}`
}

function planEndTimeChange(date) {
  taskForm.value.planEndtime =
    dayjs(date).endOf('day').format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
}

function checkFlagChange(v) {
  switch (v) {
    case '1':
    case '3':
      taskForm.value.planBegintime =
        dayjs(taskForm.value.planBegintime).format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.start)}`
      break
    case '2':
    case '4':
      taskForm.value.planEndtime =
        dayjs(taskForm.value.planEndtime).format(formatStr) + ` ${dict.getCode('work_time', checkFlag.value.end)}`
      break
  }
}

const formRef = ref()

function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      replaceTask([
        { ...taskForm.value, taskUserId: props.user.userId },
        { taskId: replaceTaskForm.value.taskId },
      ]).then((res) => {
        if (res.code === 200) {
          getTaskListByTimeData(daterange.value, props.user.userId)
          ElMessage.success('替换成功')
          close()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

function close() {
  visible.value = false
  formRef.value.resetFields()
  replaceTaskForm.value = null
  checkFlag.value = {}
}

provide('openDialog', openDialog)
</script>

<template>
  <div class="task-time-line" v-loading="loading">
    <div class="user-info">
      <el-descriptions :column="4">
        <template #title>{{ user.userName }}</template>
        <el-descriptions-item label="任务总数">{{ info.taskInfoTotal }}</el-descriptions-item>
        <el-descriptions-item label="已完成">{{ info.taskInfoDoneTotal }}</el-descriptions-item>
        <el-descriptions-item label="未完成">{{ info.taskInfoDoingTotal }}</el-descriptions-item>
        <el-descriptions-item label="超期完成">{{ info.taskInfoDelayDoneTotal }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-date-picker
      v-model="daterange"
      type="daterange"
      :unlink-panels="true"
      @change="getTaskListByTimeData(daterange, props.user.userId)"
      style="width: 100%"></el-date-picker>
    <div class="task-time-line-content">
      <WeekLine class="natural-week" v-for="week in weeks" :key="week.label" :week="week" :tasks="tasks"></WeekLine>
    </div>
    <TaskChatDialog
      v-model="visible"
      append-to-body
      @close="close"
      :title="`#${replaceTaskForm?.taskCode}-${replaceTaskForm?.taskTitle}`">
      <el-form ref="formRef" :model="taskForm" label-width="110px" :rules="rules">
        <el-form-item label="替换任务">
          <el-select
            v-model="taskForm.taskId"
            filterable
            :filter-method="filterMethod"
            @change="handleTaskChange"
            style="width: 100%">
            <el-option
              v-for="(item, index) in filterTaskList"
              :key="index"
              :label="`#${item.taskCode}-${item.taskTitle}`"
              :value="item.taskId">
              <div style="display: flex; align-items: center; justify-content: space-between">
                <span>{{ item.taskTitle }}</span>
                <span>#{{ item.taskCode }}({{ item.planCostDay }}天)</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="planBegintime">
          <el-date-picker
            :model-value="taskForm.planBegintime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="(date) => !taskForm.planEndtime || dayjs(taskForm.planEndtime).isBefore(date, 'day')"
            @update:modelValue="planStartTimeChange"
            :clearable="false"
            style="margin-right: 10px"></el-date-picker>
          <el-radio-group v-model="checkFlag.start" @change="checkFlagChange">
            <el-radio label="1">上午</el-radio>
            <el-radio label="3">下午</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndtime">
          <el-date-picker
            :model-value="taskForm.planEndtime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="(date) => !taskForm.planBegintime || dayjs(taskForm.planBegintime).isAfter(date, 'day')"
            @update:modelValue="planEndTimeChange"
            :clearable="false"
            style="margin-right: 10px"></el-date-picker>
          <el-radio-group v-model="checkFlag.end" @change="checkFlagChange">
            <el-radio label="2">上午</el-radio>
            <el-radio label="4">下午</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </TaskChatDialog>
  </div>
</template>

<style scoped lang="scss">
.task-time-line {
  display: inline-block;
  .user-info {
  }
  :deep(.elp-date-editor) {
    margin-bottom: 10px;
  }
  .task-time-line-content {
    border: var(--elp-border);
  }
}
</style>
